package com.sq.foursm.shiro;

import java.util.HashSet;
import java.util.Set;

import javax.annotation.Resource;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
/**
 * 
 * @author SQ
 * 2017年7月3日 
 * 下午3:33:48
 * 用户登陆的认证
 */
import org.apache.shiro.subject.SimplePrincipalCollection;
import org.apache.shiro.util.ByteSource;

import com.sq.foursm.entity.SecUser;
import com.sq.foursm.service.UserService;
public class UserRealm extends AuthorizingRealm  {
	@Resource
	private UserService serService;
	
	

	/**
	 * 授权
	 */
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
		//从数据库获取的角色信息(账号信息)
		String primaryPrincipal = (String)principals.getPrimaryPrincipal();
		System.out.println("--------------------------开始从数据库找寻用户信息用户是"+primaryPrincipal+"----------------------");
			Set<String> set =  new HashSet<String>();
			set.add("user:create");
			SimpleAuthorizationInfo authorizationInfo  = new SimpleAuthorizationInfo();
			authorizationInfo.addStringPermissions(set);
			//authorizationInfo.addRole("user");
			return authorizationInfo;
	}
	/**
	 * 认证
	 */
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
		//获取主体
		String principa = (String)token.getPrincipal();
		this.setName("userRealm");
		//得到的用户
		SecUser finduser = null;
		
		try {
			 finduser = serService.finduser(principa);
			
		} catch (Exception e) {
			//查询用户service异常
			e.printStackTrace();
		}
		//没有次用户
		if(finduser==null){
			throw  new UnknownAccountException("没有此用户");
		}
		//获得密码
		System.out.println("-----------------开吃查询用户"+principa+"密码是"+finduser.getPassword()+"------------------------");
		String password = finduser.getPassword();
		ByteSource bytes = ByteSource.Util.bytes("shangqi");
		SimpleAuthenticationInfo Info = new SimpleAuthenticationInfo(principa,password,bytes,this.getName()); 
		 new SimpleAuthenticationInfo();
		//8c8fd4194fe3136fc55acd2dee00211d
		return Info;
	}
	public UserService getSerService() {
		return serService;
	}
	public void setSerService(UserService serService) {
		this.serService = serService;
	}

	public void removeUserAuthorizationInfoCache(String username) {  
	    SimplePrincipalCollection pc = new SimplePrincipalCollection();  
	    pc.add(username, super.getName());  
	    super.clearCachedAuthorizationInfo(pc);  
	}  

	
	
	
	

}
